package com.my.study.java.serialization;

import com.my.study.java.bean.Company;
import io.protostuff.*;
import io.protostuff.runtime.RuntimeSchema;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Carlos
 * @version 1.0
 * @Description 序列化和反序列化工具
 * @date 2021/7/24 17:27
 **/
public class ProtostuffUtils {
    /** 避免每次序列化都重新申请Buffer空间 */
    private static LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
    /** 缓存Schema */
    private static Map<Class<?>, Schema<?>> schemaCache = new ConcurrentHashMap<>();

    /**
     * 序列化，把指定的对象序列化为字节数组
     *
     * @param obj
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> byte[] serialize(T obj) {
        Class<T> clazz = (Class<T>) obj.getClass();
        Schema<T> schema = getSchema(clazz);
        byte[] data;

        try {
            data = ProtostuffIOUtil.toByteArray(obj, schema, buffer);
        } finally {
            buffer.clear();
        }

        return data;
    }

    /**
     * 反序列化
     *
     * @param data
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T deserialize(byte[] data, Class<T> clazz) {
        Schema<T> schema = getSchema(clazz);
        T obj = schema.newMessage();
        ProtostuffIOUtil.mergeFrom(data, obj, schema);
        return obj;
    }


    @SuppressWarnings("unchecked")
    private static <T> Schema<T> getSchema(Class<T> clazz) {
        Schema<T> schema = (Schema<T>) schemaCache.get(clazz);
        if (null == schema) {
           schema = RuntimeSchema.getSchema(clazz);
           if (null != schema) {
               schemaCache.put(clazz, schema);
           }
        }

        return schema;
    }

    public static void main(String[] args) {
        // 序列化
        Company company = new Company("ths", "童话");
        byte[] serialize = ProtostuffUtils.serialize(company);
        // 反序列化
        Company deserialize = ProtostuffUtils.deserialize(serialize, Company.class);
        System.out.println(deserialize);
    }

}
